package cn.team11.smarteye.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewSwitcher;

import cn.team11.sds.dayi.R;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import net.lucode.hackware.magicindicator.buildins.UIUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.team11.smarteye.adapter.CateyeDevListAdapter;
import cn.team11.smarteye.adapter.CommonAdapter;
import cn.team11.smarteye.base.BaseActivity;
import cn.team11.smarteye.base.BaseDialog;
import cn.team11.smarteye.bean.CateyeEvent;
import cn.team11.smarteye.bean.CateyeInfoBean;
import cn.team11.smarteye.contract.DevicesListContract;
import cn.team11.smarteye.fragment.DeleteDeviceDialogFragment;
import cn.team11.smarteye.impl.DevicesListPresenterImpl;
import cn.team11.smarteye.misc.SConstants;
import cn.team11.smarteye.utils.ListUtils;
import cn.team11.smarteye.utils.ToastUtil;
import cn.team11.smarteye.widget.CustomToolbar;
import cn.team11.smarteye.widget.DividerItemDecoration;
import cn.team11.smarteye.widget.SegmentView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by Murphy on 2017/10/19.
 */

public class CateyeDeviceListActivity extends BaseActivity<DevicesListContract.Presenter> implements DevicesListContract.View, SegmentView.onSegmentViewClickListener{

    @BindView(R.id.main_segment_bt)
    SegmentView mSegmentView;
    @BindView(R.id.my_devices_title_toolbar)
    CustomToolbar mCustomBar;
    @BindView(R.id.device_view_switcher)
    ViewSwitcher mViewSwitcher;

    @BindView(R.id.no_device_layout)
    RelativeLayout mNoDeviceLayout;
    @BindView(R.id.no_devices_tips)
    TextView mNoDeviceTips;
    @BindView(R.id.swipe_cateye_refresh_layout)
    SwipeRefreshLayout cateyeSwipeLayout;
    @BindView(R.id.my_cateye_list)
    RecyclerView mCateyeList;

    @BindView(R.id.network_tips_layout)
    View mNetTipsLayout;

    private int QR_REQUEST_CODE = 10;


    private List<CateyeInfoBean> mResultList = new ArrayList<>();

    private CateyeDevListAdapter mAdapter;
    private Disposable mTimeoutDisposables;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_devices);
        ButterKnife.bind(this);

        init();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (!mTimeoutDisposables.isDisposed()){
            mTimeoutDisposables.dispose();
        }
    }

    @Override
    public void init() {
        mSegmentView.setOnSegmentViewClickListener(this);
        Drawable iconDrawable = ContextCompat.getDrawable(this, R.drawable.qr_scan);
        iconDrawable.setBounds(0, 0, UIUtil.dip2px(this, 20), UIUtil.dip2px(this, 20));
        mCustomBar.setLeftVisibility(View.INVISIBLE);
        mCustomBar.setRightVisibility(View.INVISIBLE);
        mCustomBar.setRightIcon(iconDrawable);
        mCustomBar.setBackAction(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            //    Bundle b = new Bundle();
            //    b.putString("title", getString(R.string.exit));
            //    b.putString("content", getString(R.string.exit_tips));
            //    final TextDialogFragment exitDialog = TextDialogFragment.newInstance(b);
            //    exitDialog.show(getSupportFragmentManager(), "delete_msg");
            //    exitDialog.setOnBtClickListener(new BaseDialog.OnBtClickListener() {
            //        @Override
            //        public void onConfirmClick() {
            //            finish();
            //        }

            //        @Override
            //        public void onCancelClick() {
            //            exitDialog.dismiss();
            //        }
            //    });
            }
        });
        mCustomBar.setRightAction(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(CateyeDeviceListActivity.this, QrcodeScanActivity.class);
                startActivityForResult(intent, QR_REQUEST_CODE);
            }
        });

        String tips = getResources().getString(R.string.no_dev_tips);
        SpannableString tipsSpannable = new SpannableString(getResources().getString(R.string.no_dev_tips));
        int start = tips.indexOf('\n');
        int end = tips.length();
        tipsSpannable.setSpan(new AbsoluteSizeSpan(50),0,start, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        tipsSpannable.setSpan(new AbsoluteSizeSpan(32),start+1,end,Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        mNoDeviceTips.setText(tipsSpannable);

        initRecyclerView();
        initSwipeRefresh();
        //初始化presenter
        new DevicesListPresenterImpl(this);
    }

    @Override
    public void onLoginResult(boolean result) {
        if (result){//登录成功
            if (mBasePresenter != null) mBasePresenter.getMyDevices();
        } else {//登录失败
            finishAll();
        }
    }

    @Override
    public void onNetAvailable(boolean isAvailable) {
        if (isAvailable){
            mNetTipsLayout.setVisibility(View.GONE);
            showAddViewTip();
            //登录
            if (mCateyeService != null){
                mCateyeService.cateyeLogin();
            }
        } else {
            cateyeSwipeLayout.setRefreshing(false);
            mNetTipsLayout.setVisibility(View.VISIBLE);
            showAddViewTip();
        }
    }

    @Override
    public void onCateyeServiceBinded() {

        cateyeSwipeLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshDevicesList();
            }
        });
    }


    /**
     * 初始化设备列表view
     * */
    private void initRecyclerView(){
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mCateyeList.setLayoutManager(linearLayoutManager);
        mCateyeList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        //mCateyeList.setAdapter(new CateyeListAdapter(this));
        mAdapter = new CateyeDevListAdapter(this, R.layout.device_cateye_list_item, mResultList);
        mAdapter.setOnItemClickListener(new CommonAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (mResultList.get(position).getStatus() == 1){//在线
                    Intent intent = new Intent();
                    intent.setClass(CateyeDeviceListActivity.this, CateyeDeviceDetailActivity.class);
                    intent.putExtra(SConstants.BID, mResultList.get(position).getBid());
                    intent.putExtra(SConstants.NAME, mResultList.get(position).getName());
                    startActivityForResult(intent, SConstants.DEVICE_LIST_REQUEST_CODE);

                } else {
                    showToast(ToastUtil.NEGATIVE_TOAST, getString(R.string.device_is_offline));
                }

            }
        });
        mAdapter.setOnItemLongClickListener(new CommonAdapter.OnItemLongClickListener() {
            @Override
            public void onItemLongClick(View view, final int position) {
                final DeleteDeviceDialogFragment deleteDeviceDialogFragment = new DeleteDeviceDialogFragment();
                deleteDeviceDialogFragment.show(getSupportFragmentManager(), "delete");
                deleteDeviceDialogFragment.setOnBtClickListener(new BaseDialog.OnBtClickListener() {
                    @Override
                    public void onConfirmClick() {
                        if (mBasePresenter != null) {
                            mBasePresenter.deleteDevice(mResultList.get(position).getBid());
                            mResultList.remove(position);
                            mAdapter.notifyDataSetChanged();
                        }
                        deleteDeviceDialogFragment.dismiss();
                    }

                    @Override
                    public void onCancelClick() {
                        deleteDeviceDialogFragment.dismiss();
                    }
                });
            }
        });
        mCateyeList.setAdapter(mAdapter);
    }

    private void initSwipeRefresh(){
        cateyeSwipeLayout.setColorSchemeResources(R.color.color_main_green);
        cateyeSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //presenter更新数据
                cateyeSwipeLayout.setRefreshing(true);
                if (mBasePresenter != null)
                    mBasePresenter.getMyDevices();
                createTimer();
            }
        });
    }

    private void refreshDevicesList(){
        createTimer();
        cateyeSwipeLayout.setRefreshing(true);//一打开先刷新
        if (mBasePresenter!=null){
            //先登录，登录成功后再获取设备列表
            if (mCateyeService != null) {
                if (mCateyeService.isUserLogin()){
                    mBasePresenter.getMyDevices();
                } else {
                    mCateyeService.cateyeLogin();
                }
            } else {
                cateyeSwipeLayout.setRefreshing(false);
                //猫眼服务未开启，以后添加服务重启
                showToast(ToastUtil.NEGATIVE_TOAST, "猫眼服务未启动");
                finishAll();
            }
        }
    }

    @Override
    public void onSegmentViewClick(View view, int postion) {
        if (postion == 0){//左边按钮
            //mCustomBar.setMidTitle(getResources().getString(R.string.doorlock));
            //mViewSwitcher.showNext();
            finishAll();
            overridePendingTransition(0, 0);
        } else if (postion == 1){//右边按钮
            mCustomBar.setMidTitle(getResources().getString(R.string.cateye));
            mViewSwitcher.showPrevious();
        }

    }

    @OnClick(R.id.add_device)
    public void addCatEyeDevice(View view){
        //检查登录状态
        if (mCateyeService != null){
            if (!mCateyeService.isUserLogin()){
                showToast(ToastUtil.NEGATIVE_TOAST, "请先登录再进行绑定");
            } else {
                int idx = mSegmentView.getSelect();
                if (idx == SegmentView.RIGHT_INDEX){//当前为猫眼
                    Intent intent = new Intent();
                    intent.setClass(this, DeviceConfigActivity.class);
                    startActivityForResult(intent,SConstants.DEVICE_LIST_REQUEST_CODE);
                } else if (idx == SegmentView.LEFT_INDEX) {//当前为门锁

                }
            }
        }


    }

    @Override
    public void setPresenter(DevicesListContract.Presenter presenter) {
        this.mBasePresenter = presenter;
    }


    @Override
    public Context getContext() {
        return getApplicationContext();
    }

    /**
     * 用于更新设备列表
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeviceListFound(CateyeEvent.DevicesFoundEvent event){
        if (!mTimeoutDisposables.isDisposed()) mTimeoutDisposables.dispose();
        //暴力刷新，先清除原数据
        mResultList.clear();
        cateyeSwipeLayout.setRefreshing(false);//停止刷新动画
        if (ListUtils.isEmpty(event.getDevices())){
            //显示添加设备提示View
            mNoDeviceLayout.setVisibility(View.VISIBLE);
        } else {
            //不显示添加设备提示View
            mNoDeviceLayout.setVisibility(View.INVISIBLE);
            //停止刷新
            for (CateyeInfoBean item : event.getDevices()){
                mResultList.add(item);
            }
        }
        mAdapter.notifyDataSetChanged();

    }

    @Override
    public void onBackPressed() {

    }

    private void showAddViewTip(){

        if (ListUtils.isEmpty(mResultList)){
            mNoDeviceLayout.setVisibility(View.VISIBLE);
        } else {
            mNoDeviceLayout.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        refreshDevicesList();
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == QR_REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    showToast(ToastUtil.POSITIVE_TOAST, result);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    showToast(ToastUtil.NEGATIVE_TOAST, "解析二维码失败");
                }
            }
        }

    }
    private void createTimer(){
        mTimeoutDisposables = Observable.interval(0, 1, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Long>() {
            @Override
            public void accept(Long aLong) throws Exception {
                if (aLong == 10){//timeout
                    mTimeoutDisposables.dispose();
                    //显示添加设备提示View
                    showAddViewTip();
                }
            }
        });
    }

}
